/**
 * Created by chenyong on 2015/7/16.
 */

var passport = require('passport');
var config = require('../config');
var jwt = require('jsonwebtoken');
var expressJwt = require('express-jwt');
var compose = require('composable-middleware');
var validateJwt = expressJwt({ secret: config.secrets.session });

//判断用户是否登录
function isAuthenticated() {
    return compose()
        // 验证jwt
        .use(function(req, res, next) {
            if(req.query && req.query.hasOwnProperty('access_token')) {
                req.headers.authorization = 'Bearer ' + req.query.access_token;
            }
            validateJwt(req, res, next);
        })
        // 附加用户信息到Request中
        .use(function(req, res, next) {

            var userId = req.user._id;
            var userinfo = {_id:userId};
            req.user = userinfo;
            next();
            //略过
            //userId = req.user._id;
            //req.user = {userinfo}
        });
}

function hasRole(roleRequired) {
    if (!roleRequired) throw new Error('Required role needs to be set');

    return compose()
        .use(isAuthenticated())
        .use(function meetsRequirements(req, res, next) {
            if (config.userRoles.indexOf(req.user.role) >= config.userRoles.indexOf(roleRequired)) {
                next();
            }
            else {
                res.send(403);
            }
        });
}

//返回一个加密令牌
function signToken(id) {
    return jwt.sign({ _id: id }, config.secrets.session, { expiresInMinutes: 60*5 });
}

//为OAuth登录设置令牌
function setTokenCookie(req, res) {
    if (!req.user) return res.json(404, { message: '系统出错, 请再试一次.'});
    var token = signToken(req.user._id, req.user.role);
    res.cookie('token', JSON.stringify(token));
    //res.render('auth/callback');
    res.redirect('/auth/success');
}

exports.setTokenCookie = setTokenCookie;
exports.isAuthenticated = isAuthenticated;
exports.signToken = signToken;